package com.itheima.loginTest;

import com.itheima.loginMapper.User;
import com.itheima.loginMapper.UserMapper;
import com.itheima.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: yg
 * @create 2025-02-07 - 21:53
 * @
 */
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接受用户名密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        UserMapper mapper = MyBatisUtils.getMapper(UserMapper.class);
        User user1 = mapper.selectByUsername(username);
        if(user1 == null){
            mapper.addUser(user);
            SqlSession session = MyBatisUtils.GetSqlSessionFromMapper(mapper);
            session.commit();
            MyBatisUtils.closeSession(mapper);
        }else{
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter pw = resp.getWriter();
            pw.write("该用户名已被占用");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }


}
